from fastapi import APIRouter, Request
from starlette.responses import JSONResponse
from models.models import SysUser
import hashlib
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

sys = APIRouter()

@sys.get("/login")
async def login(request: Request):
    """
    系统用户登录接口
    """
    try:
        username = request.query_params.get("username")
        password = request.query_params.get("password")
        
        # 检查用户名是否提供
        if not username:
            return JSONResponse({"code": 400, "message": "请输入用户名"})
        
        # 检查密码是否提供
        if not password:
            return JSONResponse({"code": 400, "message": "请输入密码"})
        
        # 查找用户
        sysuser = await SysUser.filter(username=username).first()
        if not sysuser:
            logger.warning(f"登录失败：用户名不存在 - {username}")
            return JSONResponse({"code": 400, "message": "用户名或密码错误"})
        
        # 注意：根据数据库查询结果，系统直接存储了明文密码而不是哈希值
        # 所以我们直接比较密码而不是比较哈希值
        if sysuser.password_hash == password:
            logger.info(f"用户登录成功 - {username}")
            return JSONResponse({"code": 200, "message": "登录成功"})
        else:
            logger.warning(f"登录失败：密码错误 - {username}")
            return JSONResponse({"code": 400, "message": "用户名或密码错误"})
            
    except Exception as e:
        logger.error(f"登录过程中发生错误: {str(e)}")
        return JSONResponse({"code": 500, "message": "服务器内部错误"})